
package week9

import (
	"bufio"
	"encoding/binary"
	"io"
)

//goim协议
//packLen 包长度【4bytes】
//headerLen 头长度【2bytes】
//proto.Ver 协议版本号【2bytes】
//proto.Operation 业务操作码【4bytes】
//proto.Seq 序列号【4bytes】
//body 包内容

// Proto proto.
type Proto struct {
	PackLen   int32  // package length
	HeaderLen int16  // header length
	Ver       int16  // protocol version
	Operation int32  // operation for request
	Seq       int32  // sequence number chosen by client
	Body      []byte // body
}

//读取协议内容【参照goim-client】
func ReadProto(rd *bufio.Reader, proto *Proto) (err error)  {
	if err = binary.Read(rd, binary.BigEndian, &proto.PackLen); err != nil {
		return
	}
	if err = binary.Read(rd, binary.BigEndian, &proto.HeaderLen); err != nil {
		return
	}
	if err = binary.Read(rd, binary.BigEndian, &proto.Ver); err != nil {
		return
	}
	if err = binary.Read(rd, binary.BigEndian, &proto.Operation); err != nil {
		return
	}
	if err = binary.Read(rd, binary.BigEndian, &proto.Seq); err != nil {
		return
	}

	bodyLen := int(proto.PackLen - int32(proto.HeaderLen))
	if bodyLen > 0 {
		proto.Body = make([]byte, bodyLen)
		io.ReadFull(rd, proto.Body)
	} else {
		proto.Body = nil
	}
	return
}